<script setup>
import { onUnmounted, ref, watch } from 'vue';
import { useEcharts } from '@/hooks/common/echarts';
import { useDictStore } from '@/store/modules/dict';

const props = defineProps({
  list: {
    type: Array,
    default: () => []
  }
});

const { store } = useDictStore();

const pieData = ref([]);
const pieDataWatch = watch(
  () => store.drilling_equipment_state,
  val => {
    pieData.value = val?.map(item => {
      return {
        key: item.value,
        name: item.label,
        value: 0
      };
    });
  },
  { deep: true }
);

const { domRef, updateOptions } = useEcharts(
  () => ({
    tooltip: {
      trigger: 'item'
    },
    title: {
      text: '设备状态统计',
      left: 'center',
      top: '15',
      textStyle: {
        color: '#646cff',
        fontWeight: 'bold',
        fontSize: '1.5rem'
      }
    },
    legend: {
      bottom: '1%',
      left: 'center',
      itemStyle: {
        borderWidth: 0
      }
    },
    series: [
      {
        color: ['#1CD66C', '#8e9dff', '#FF3030', '#26deca', '#fedc69'],
        name: '设备状态',
        type: 'pie',
        radius: ['45%', '70%'],
        avoidLabelOverlap: false,
        center: ['50%', '50%'], // 将饼图的中心位置往上移动
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          show: false,
          position: 'center'
        },
        // emphasis: {
        //   label: {
        //     show: true,
        //     fontSize: '12'
        //   }
        // },
        labelLine: {
          show: false
        },
        data: pieData.value
      }
    ]
  }),
  false
);

function countKeyOccurrences(arr) {
  return arr.reduce((acc, obj) => {
    // if (obj[key]) {
    //   acc[obj[key]] = (acc[obj[key]] || 0) + 1;
    // }
    if (obj.equipmentStatus) {
      acc[obj.equipmentStatus] = (acc[obj.equipmentStatus] || 0) + 1;
    }
    return acc;
  }, {});
}
watch(
  () => props.list,
  val => {
    const obj = countKeyOccurrences(val);
    pieData.value.forEach(item => {
      item.value = obj[item.key];
    });
    updateOptions(opts => {
      opts.series[0].data = pieData.value;
      return opts;
    });
  },
  { deep: true }
);

onUnmounted(() => {
  pieDataWatch();
});
</script>

<template>
  <div ref="domRef" class="h-360px overflow-hidden"></div>
</template>

<style scoped></style>
